package com.kfm.jdbc.day0404;


import com.kfm.jdbc.day0328.DBUtils;

import java.lang.reflect.*;
import java.util.List;

public class Mybatis {


    public <T extends Mapper> T getMapper(Class<T> clazz) {
        // 通过代理模式，返回一个代理对象
        T t = (T)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 调用方法名
                String methodName = method.getName();

                Select annotation = method.getAnnotation(Select.class);
                if (annotation != null){
                    String sql = annotation.value();
                    // 通过正则表达式获取参数
                    sql = sql.replaceAll("#\\{arg[0-9]+}", "?");

//                    StringBuilder prepareedSql = new StringBuilder();
//                    // 拼接参数
//                    for (int i = 0; i < split.length; i++) {
//                        prepareedSql.append(split[i] + args[i]);
//                    }
//
//                    System.out.println(prepareedSql);
                    System.out.println(sql);

                    Class<?> returnType = method.getReturnType(); // List
                    // 判断 returnType 是否是 List
                    if (returnType.isAssignableFrom(List.class)){
                        // 获取返回值类型
                        Type genericReturnType = method.getGenericReturnType(); // List<Goods>
                        if (genericReturnType instanceof ParameterizedType){
                            // 泛型类型
                            ParameterizedType type = (ParameterizedType) genericReturnType;
                            Type[] typeArguments = type.getActualTypeArguments();
                            Type typeArgument = typeArguments[0];
                            if (typeArgument instanceof Class){
                                Class<?> typeArgumentClass = (Class<?>) typeArgument;
                                // 执行操作
                                DBUtils dbUtils = new DBUtils<>(1);

                                return dbUtils.select(sql, typeArgumentClass, args);
                            }
                        }

                    } else {
                        // 执行操作
                        DBUtils dbUtils = new DBUtils<>(1);

                        return dbUtils.selectOne(sql, returnType, args);
                    }


                }
                if ("toString".equals(methodName)){
                    return "Proxy";
                }
                return null;
            }
        });
        return t;
    }
}
